<template>
  <div class="login">
    <h1 class="logo">
      {{ system }}
    </h1>
    <div class="login-bodyNew">
      <div class="wrap">
        <div class="login-form">
          <h2>用户登录</h2>
          <!-- {{process.env.VUE_APP_publicPath}} -->
          <p class="login-name">
            <input id="username" v-model="loginModel.username" type="text" placeholder="用户名" />
            <label class="el-icon-user" for="username" />
          </p>
          <p class="login-password">
            <input
              id="password"
              v-model="loginModel.password"
              type="password"
              placeholder="密码"
              @keyup.enter="submitFn"
            />
            <label class="el-icon-lock" for="password" />
          </p>
          <!-- <p>
            <input
              type="text"
              id="kaptcha"
              style="width: 90px;height:34px;font-size:18px;line-height:1.8;border: 1px solid #ccc;text-indent: 10px;margin-bottom: 5px;"
              v-model="loginModel.kaptcha"
              maxlength="6"
              name="kaptcha"
              placeholder="验证码"
            />
            <img v-bind:src="imgUrl" width="80" height="34" alt="验证码" />
            <a href="javascript:void(0)" class="changeCaptcha" @click="freshImg"
              >换一张</a
            >
          </p> -->
          <p class="login-code">
            <input
              id="kaptcha"
              v-model="loginModel.kaptcha"
              type="text"
              name="kaptcha"
              maxlength="6"
              placeholder="输入右侧验证码"
              @keyup.enter="submitFn"
            />
            <label for="kaptcha" class="icon-code" />
            <span title="点击刷新" class="code" @click="freshImg">
              <img :src="imgUrl" alt="验证码" />
            </span>
          </p>
          <p class="login-option" style="margin: 20px 0">
            <span class="option-left">
              <!-- <el-checkbox v-model="checked" checked>记住账号</el-checkbox> -->
            </span>
          </p>
          <p class="login-submit">
            <el-button type="primary" size="large" :loading="submitLoadingFlag" @click="submitFn">登录</el-button>
          </p>
          <p class="login-option">
            <span class="option-right">
              <!-- <el-link type="primary" @click="register">注册</el-link>
                            <el-link type="info">忘记密码</el-link> -->
            </span>
          </p>
        </div>
      </div>
      <div v-if="systemRight" class="login-footer">
        {{ systemRight }}
      </div>
      <!-- <div v-else class="login-footer">
        {{ title }} © 1998-{{ nowYear }} Glodon
      </div> -->
    </div>
  </div>
</template>
<script>
  import { JSEncrypt } from "jsencrypt";
  // import md5 from "js-md5";
  import { setItem } from "@/utils/storage.js";
  import { mapActions } from "vuex";
  import {
    //   获取验证码
    // 获取PublicKey
    // 登录
    // 获取系统、菜单、用户信息
    loginPublicKey,
    loginToLogin
  } from "../api/api";
  // import { setCookie } from "../utils/utils";
  export default {
    data() {
      return {
        gfmlogin: `${process.env.API_HOST}/commonlogin/toLogin`,
        getIndexDataUrl: `${process.env.API_HOST}/common/getIndexData`, // 获取登录成功后默认系统
        imgUrl: "",
        loginModel: {
          username: "",
          password: "",
          kaptcha: ""
        },
        publicKey: "",
        token: "",
        nowYear: 2022,
        submitLoadingFlag: false,
        loading: false,
        checked: true,
        title: process.env.VUE_APP_SYS_NAME
      };
    },
    computed: {
      system() {
        console.log("sss", this.$store.getters.system);
        document.title = this.$store.getters.system;
        return this.$store.getters.system;
      },
      systemRight() {
        console.log("system", this.$store.getters.system);
        return this.$store.getters.systemRight;
      }
    },
    async created() {
      window.messageBoxFlag = false;
      await this.systemPrivilegeInfoFn();
    },
    mounted: function () {
      // location.href = "/fw/#/login";
      // document.title = this.system || this.title;
      this.freshImg();
    },
    methods: {
      ...mapActions([
        "setSystemAction",
        "systemPrivilegeInfoFn",
        "setHeadNavAction" // 将 `this.setHeadNavFn(amount)` 映射为 `this.$store.dispatch('setHeadNavFn', amount)`
      ]),
      encryptedData(publicKey, data) {
        // new Date().getFullYear()
        // // 新建JSEncrypt对象
        // let encryptor = new JSEncrypt();
        // // 设置公钥
        // encryptor.setPublicKey(publicKey);
        // // 加密数据
        // return encryptor.encrypt(data);
        // var publicKey = res.data.public_key;
        // 加密操作
        const encrypt = new JSEncrypt();
        encrypt.setPublicKey(publicKey); // 设置公钥
        return encrypt.encrypt(data);
      },
      async submitFn() {
        if (this.submitLoadingFlag) {
          return;
        }
        this.submitLoadingFlag = true;
        this.setFlag = setTimeout(() => {
          this.submitLoadingFlag = false;
        }, 30000);
        // if (!this.loading) {
        //   this.unableLogin();
        // }
        await this.getPublicKeyFn();
        let { username, password, kaptcha } = this.loginModel;
        const rule = {
          username: {
            value: username,
            message: "用户名不能为空"
          },
          password: {
            value: password,
            message: "密码不能为空"
          },
          kaptcha: {
            value: kaptcha,
            message: "验证码不能为空"
          }
        };
        const noPassKey = Object.keys(rule).find((key) => !rule[key].value);
        if (noPassKey) {
          this.enableLogin();
          this.$message.error(rule[noPassKey].message);
          return;
        }
        password = this.encryptedData(this.publicKey, password);
        const params = {
          username: username,
          password: password,
          kaptcha: kaptcha
          // 'contentType':1 //区分请求头内容类型标识
        };
        try {
          const res = await loginToLogin(params);
          console.log("res", res);
          // localStorage.setItem("username", username);
          localStorage.setItem("username", "");
          // this.setSystemAction({ username });
          if (res.code === 0) {
            this.$message({
              message: "登录成功",
              type: "success",
              duration: 1000,
              single: true,
              onClose: () => {
                // 左侧导航登录时跳转 和 刷新导航不变用到
                // sessionStorage.default_num = 1;
                // sessionStorage.default_system = "";
                this.$router.push({
                  name: "Home"
                });
              }
            });
          } else {
            this.$message({
              message: res.msg || "获取系统数据失败,无法跳转",
              type: "error",
              duration: 2000,
              single: true,
              onClose: () => {}
            });
            this.enableLogin();
            this.freshImg();
          }
        } catch (e) {
          console.error(e);
          this.$message({
            message: "获取系统数据失败,无法跳转",
            type: "error",
            duration: 2000,
            single: true,
            onClose: () => {}
          });
          this.enableLogin();
          this.freshImg();
        }
      },
      async getPublicKeyFn() {
        if (!this.loading) {
          // this.unableLogin();
          // this.$router.replace({
          //   name: "Home"
          // });
          const key = this.randomString(11);
          try {
            const o = {
              r: key
            };
            const res = await loginPublicKey(o);
            if (res.code == 0) {
              this.publicKey = res.public_key;
              setItem("token", this.publicKey);
              // this.submitFn();
            } else {
              this.$message({
                message: "登录初始化失败",
                type: "error",
                iconClass: "el-icon-error"
              });
            }
          } catch (e) {
            console.error(e);
            clearTimeout(this.setFlag);
            this.submitLoadingFlag = false;
            this.$message({
              message: "登录初始化失败",
              type: "error",
              iconClass: "el-icon-error"
            });
          }
        }
      },
      randomString(len1) {
        const len = len1 || 32;
        const $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
        const maxPos = $chars.length;
        let pwd = "";
        for (let i = 0; i < len; i++) {
          pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
      },
      async freshImg() {
        // 验证码
        // loginKaptchaImage
        this.imgUrl = `${process.env.VUE_APP_API}/platform/getKaptchaImage?_${new Date().getTime()}`;
      },
      register() {
        this.$router.push({
          name: "register"
        });
      },
      log(msg) {
        if (window["console"]) {
          console.log(msg);
        }
      },
      enableLogin() {
        this.loading = false;
        this.submitLoadingFlag = false;
      },
      unableLogin() {
        this.loading = true;
        this.submitLoadingFlag = true;
      }
    }
  };
</script>
<style lang="scss" scoped>
  // 登录
  .login {
    // background-image: url("~@/assets/imgs/banner.png");
    background-repeat: no-repeat;
    background-size: 100% 50%;
    min-width: 500px;
    min-height: 500px;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    top: 0;
    &::before {
      content: "";
      display: block;
      position: fixed;
      top: 0;
      z-index: -1;
      background-color: #339bf5;
      width: 100%;
      height: 50%;
    }
    .logo {
      height: 70px;
      line-height: 70px;
      font-size: 26px;
      font-weight: bolder;
      color: #fff;
      margin-left: 20px;
    }
    // 更换背景图 换新的类名
    .login-bodyNew {
      // @include clear;
      // height: 44%;
      height: 480px;
      // width: 100%;
      width: auto;
      // background: #f2f2f2;
      // background: #f2f2f2 url(../assets/imgs/bg.png) 0 0 no-repeat;
      // background-size: 100% 100%;
      // background:red;
      margin: 0 auto;
      .wrap {
        // @include clear;
        // width: 1200px;
        margin: 10px auto;
      }
    }
    .login-form {
      // @include float(right);
      border-radius: 10px;
      position: relative;
      // top: -23px;
      width: 400px;
      padding: 0 30px;
      // height: 530px;
      background-color: #fff;
      box-shadow: 8px 0px 25px 0px rgba(145, 196, 255, 0.2);
      // &::before {
      //   position: absolute;
      //   left: -16px;
      //   content: "";
      //   width: 0;
      //   height: 0;
      //   border-width: 0 0 24px 16px;
      //   border-style: solid;
      //   border-color: transparent transparent #2d6db2 transparent;
      // }
      h2 {
        font-size: 24px;
        color: $primary;
        text-align: center;
        font-weight: bolder;
        padding: 30px 0 30px 0;
      }
    }
    .login-code {
      position: relative;
      label {
        position: absolute;
        display: block;
        width: 30px;
        height: 26px;
        line-height: 26px;
        top: 12px;
        left: 5px;
        color: #888;
        text-align: center;
        font-size: 16px;
      }
      input {
        -webkit-transition-duration: 0.3s;
        transition-duration: 0.3s;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        display: block;
        width: 100%;
        height: 50px;
        line-height: 50px;
        font-size: 16px;
        color: #555;
        padding: 0 3px;
        padding-left: 40px;
        border: none;
        border-bottom: 1px solid #d2d2d2;
      }
      .code {
        position: absolute;
        cursor: pointer;
        top: 5px;
        right: 0;
        height: 38px;
        img {
          width: 125px;
          height: 45px;
        }
      }
      // .icon-code:before {
      //   content: "\E636";
      // }
    }
    .login-name,
    .login-password {
      position: relative;
      margin-bottom: 30px;
      label {
        position: absolute;
        display: block;
        width: 30px;
        height: 26px;
        line-height: 26px;
        top: 11px;
        left: 5px;
        color: $icon;
        text-align: center;
        font-size: 16px;
      }
      input {
        @include transition;
        box-sizing: border-box;
        display: block;
        width: 100%;
        height: 50px;
        line-height: 50px;
        font-size: 16px;
        color: $gray;
        padding: 0 3px;
        padding-left: 40px;
        border: none;
        border-bottom: 1px solid $line;
        &:hover,
        &:focus {
          border-color: $primary;
        }
        &:hover + label,
        &:focus + label {
          color: $primary;
          border-color: $primary;
        }
      }
    }
    .login-option {
      @include clear;
      margin: 50px 0 20px 0;
      .option-left {
        @include float;
      }
      .option-right {
        @include float(right);
      }
      .forget-password {
        color: $gray;
        cursor: help;
      }
    }
    .login-submit {
      button {
        display: block;
        width: 100%;
        height: 50px;
        font-size: 18px;
      }
    }
    .login-footer {
      text-align: center;
      width: 100%;
      font-size: 14px;
      color: $gray;
      padding: 20px 0;
      margin: 0 auto;
    }
  }
</style>
